import axios from 'axios';
import qs from 'Qs';
import { Dialog, Toast } from 'vant';

// let mock_api = "https://easy-mock.com/mock/5b889f54ce613155abd99ffe";
let test_api = "https://t.liyboo.com";//测试
let deploy_api = "https://m.jinzhishenghuo.com"; //正式
// let httpUrl = 'http://192.168.0.132:8001';
// let httpUrl = 'http://192.168.0.184:8001';
// let httpUrl = 'http://192.168.0.129:8001';
let httpUrl = 'http://localhost:8001';
let instance = axios.create({
	timeout: 30000,
	baseURL: deploy_api
	//  baseURL: httpUrl
	// baseURL: test_api
});

let authToken = null;

const getToken = () => {
	if (authToken) {
		return authToken;
	}

	authToken = window.localStorage.getItem('authToken');
	return authToken;
}

instance.interceptors.request.use( (config) => {
	!config.hideLoading && Toast.loading({mask: true, duration: 0});
	if (config.method === 'post' || config.method === 'put') {
		if (config.dataType !== "json") {
			config.data = qs.stringify(config.data);
		}
	}
	if (!config.headers.Authorization) {
		config.headers.Authorization = getToken() || 'empty-token';
	}
	return config;
}, (err) => {
	return Promise.reject(err);
});

instance.interceptors.response.use( (res) => {
	Toast.clear();

	if (res.data.code === undefined) {
		return res;
	}

	if (res.data.code !== 0 && !res.data.success) {
		switch (res.data.code) {
			case 422:
				var flag = Array.isArray(res.data.data) && res.data.data.length;
				Dialog.alert({message: flag ? res.data.data[0].msg : res.data.msg})
				break;
			case 401:
				break;
			case 404:
				break;
			case 408:
				Dialog.alert({message: '网络请求超时，请稍后刷新重试'});
				break;
			default:
				if (res.data.msg) {
					Dialog.alert({message: res.data.msg});
				}
				break;
		}
		return Promise.reject(res);
	}
	return res;
}, (error) => {
	Toast.clear();
	let message = '服务正忙，请刷新重试';

	if (error.response) {
		switch (error.response.status) {
			case 413:
			message = "上传文件超过大小限制";
			break;
		}
	}

	Dialog.alert({
	  title: '警告',
	  message: message
	})
	return Promise.reject(error);
});

const post = (url, data, config = {}) => {
	return instance.post(url, data, config)
}

const put = (url, data, config = {}) => {
	return instance.put(url, data, config)
}

const get = (url, params, config = {}) => {
	return instance.get(url, {
		params: params,
		...config
	})
}

const deleteMethod = (url, config = {}) => {
	return instance({
		url: url,
		method: 'delete',
		...config
	})
}

export default {
	install(Vue) {
		Object.defineProperties(Vue.prototype, {
			$reqGet: {
				value: get
			},
			$reqPost: {
				value: post
			},
			$reqPut: {
				value: put
			},
			$reqDel: {
				value: deleteMethod
			},
			$deployApi: {
				value: deploy_api
			}
		})
	}
}
